// validators/is-valid-string-list.validator.ts
import {
    registerDecorator,
    ValidationArguments,
    ValidationOptions,
    ValidatorConstraint,
    ValidatorConstraintInterface
} from "class-validator";

@ValidatorConstraint({ name: "isValidStringList", async: false })
class IsValidStringListConstraint implements ValidatorConstraintInterface {
    validate(value: any, args: ValidationArguments): boolean {
        if (typeof value !== "string") return false;
        const [allowed] = args.constraints;
        const parts = value.split(",").map(part => part.trim());
        return parts.every(part => allowed.includes(part));
    }

    defaultMessage(args: ValidationArguments): string {
        const [allowed] = args.constraints;
        // return `通道参数必须是由 ${ALLOWED_CHANNELS.join(", ")} 组成的逗号分隔字符串`;
        return `${args.property} must be a comma-separated list of the following values: ${allowed.join(",")}`;
    }
}

/**
 * 验证字符串是否是由指定字符串数组组成的逗号分隔字符串
 * @param allowedValues 允许的字符串数组列表
 * @param validationOptions 验证选项
 * @returns 验证器装饰器函数
 */
export function IsValidStringList(allowedValues: string[], validationOptions?: ValidationOptions) {
    return function (object: object, propertyName: string) {
        registerDecorator({
            target: object.constructor,
            propertyName: propertyName,
            options: validationOptions,
            constraints: [allowedValues],
            validator: IsValidStringListConstraint
        });
    };
}
